{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from Crypto import Random\n",
    "from Crypto.Cipher import AES"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## AES-CBC"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def encrypt(plaintext):\n",
    "    # initialize AES\n",
    "    random = Random.new()\n",
    "    iv = random.read(16)\n",
    "    key = random.read(16)\n",
    "    aes = AES.new(key, AES.MODE_CBC, iv)\n",
    "\n",
    "    # add PKCS#7 padding\n",
    "    pad = 16 - len(plaintext) % 16\n",
    "    plaintext += bytes([pad] * pad)\n",
    "    \n",
    "    # encrypt\n",
    "    ciphertext = iv + aes.encrypt(plaintext)\n",
    "\n",
    "    return key, ciphertext"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def decrypt(ciphertext, key):\n",
    "    # initialize AES\n",
    "    iv = ciphertext[:16]\n",
    "    aes = AES.new(key, AES.MODE_CBC, iv)\n",
    "\n",
    "    # decrypt\n",
    "    plaintext = aes.decrypt(ciphertext[16:])\n",
    "    \n",
    "    # check PKCS#7 padding\n",
    "    pad = plaintext[-1]\n",
    "    if pad not in range(1, 17):\n",
    "        raise Exception()\n",
    "    if plaintext[-pad:] != bytes([pad] * pad):\n",
    "        raise Exception()\n",
    "\n",
    "    # remove padding\n",
    "    return plaintext[:-pad]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## secure service"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def secure_service(message):\n",
    "    secret_key = b'\\xed\\xcc\\xb5\\x8a\\xf4\\x8f\\xd9\\x1e\\x1bS\\xce~p\\xa2s\\xcc'\n",
    "\n",
    "    # decrypt message\n",
    "    plaintext = decrypt(message, secret_key)\n",
    "\n",
    "    # process message\n",
    "    try:\n",
    "        from json import loads\n",
    "        print('ACK', loads(plaintext))\n",
    "    except Exception:\n",
    "        raise ValueError()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## adversarial client"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def attack(message):\n",
    "    reconstructed = b''\n",
    "\n",
    "    while len(message) >= 32:\n",
    "        # retrieved block\n",
    "        block = [0] * 16\n",
    "\n",
    "        # byte in block\n",
    "        for i in range(1, 17):\n",
    "            # PKCS#7 padding\n",
    "            pad = [0] * (16 - i) + [i] * i\n",
    "\n",
    "            for x in range(256):\n",
    "                # tested byte\n",
    "                block[-i] = x\n",
    "                if x == i:\n",
    "                    continue\n",
    "                \n",
    "                # alter message\n",
    "                test = bytearray(message)\n",
    "                for j in range(16):\n",
    "                    test[-32 + j] ^= block[j] ^ pad[j]\n",
    "                test = bytes(test)\n",
    "\n",
    "                try:\n",
    "                    # call service\n",
    "                    secure_service(test)\n",
    "                except ValueError as e:\n",
    "                    break  # incorrect content\n",
    "                except Exception as e:\n",
    "                    pass   # incorrect padding\n",
    "            else:\n",
    "                block[-i] = i\n",
    "\n",
    "        # store retrieved block and continue\n",
    "        reconstructed = bytes(block) + reconstructed\n",
    "        message = message[:-16]\n",
    "\n",
    "    return reconstructed"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "intercepted_message = b'\\xd97\\xea\\xc8\\xfe\\xdf\\x06\\xf7b3\\x16UG\\xd5#>\\xa8\\x1c.l\\xf1+\\xc9H\\xbd\\xb1\\x91\\x90\\xc0\\xac?\\x92\\x1c\\xa0\\x08\\xc7d/\\x10\\xe6\\xae\\xe0 F\\x1a\\x13\\xc1\\xb0\\xf0,\\xd7\\xb9\\xca\\xfb\\xde\\x13\\xa5\\xfd92\\xff*\\x17\\xbc\\x8f\\xd3Z\\xe81\\x8f\\x1c\\xb4\\x17@\\xeb5\\t\\xa4\\x16\\xb2\\x07\\x06\\xd6\\x83x\\xac\\xf3\\xc9\\xb2\\xb7\\xf6Q3\\xc0\\x7f\\x92\\xd4p\\xfeV\\xad{\\xc7(}\\x8f[L>\\x08\\xab\\xfe'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "b'{\"user\":\"John Doe\",\"message\":\"and what is your favorite way to screw your security up?\"}\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08'"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "attack(intercepted_message)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
